package com.witmed.user

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.Gson
import com.witmed.lib_common.ActivityPath
import com.witmed.user.databinding.ActivityRegCodeBinding
import com.witmed.user.intent.UserIntent
import com.witmed.user.viewmodel.RegisterState
import com.witmed.user.viewmodel.RegisterViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.RequestBody
import java.util.Timer
import java.util.TimerTask
import kotlin.concurrent.timerTask

@Route(path = ActivityPath.PAGE_REGISTERCODE)
class RegCodeActivity : AppCompatActivity() {
    lateinit var db:ActivityRegCodeBinding
    lateinit var vm:RegisterViewModel
    var code=""

    var time=10
    val handler=Handler()
    private val myTimer=object :Runnable{
        override fun run() {
            //主线程更新UI
            db.btnSend.text="验证码（$time s）"
            db.btnSend.isEnabled=false
            if(time>0){
                handler.postDelayed(this,1000)
            }else{
                db.btnSend.isEnabled=true
                db.btnSend.text="重新发送"
                time=10
            }
            time--
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        db=ActivityRegCodeBinding.inflate(layoutInflater)
        setContentView(db.root)
        //获取ViewmModel
        vm= ViewModelProvider(this).get(RegisterViewModel::class.java)

        //接收状态
        lifecycleScope.launch {
            vm.registerState.collect{
                when(it){
                    is RegisterState.RegCodeSuccess->{
                        code=it.code
                        Log.i("Activity",code.toString())
                        //获取通知系统服务
                        val manager=getSystemService(NOTIFICATION_SERVICE) as NotificationManager
                        //针对sdk>=26以上的系统获取通知服务
                        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
                            val channel=NotificationChannel("normal","normal",NotificationManager.IMPORTANCE_DEFAULT)
                            manager.createNotificationChannel(channel)
                        }
                        val intent = Intent(this@RegCodeActivity, RegCodeActivity::class.java)
                        val pendingIntent = PendingIntent.getActivity(this@RegCodeActivity, 0, intent,
                            PendingIntent.FLAG_MUTABLE)
                        val notification = NotificationCompat.Builder(this@RegCodeActivity, "normal")
                            .setContentTitle("验证码")
                            .setContentText("发送的验证码是：$code,请在30秒内使用")
                            .setSmallIcon(R.drawable.ic_launcher_background)
                            .setContentIntent(pendingIntent)
                            .setAutoCancel(true)
                            .build()
                        manager.notify(1,notification)
                    }
                    //验证码注册成功的状态
                    is RegisterState.RegisterCodeSuccess->{
                        ARouter.getInstance().build(ActivityPath.PAGE_LOGINCODE).navigation()
                    }
                    is RegisterState.Error->{
                        Toast.makeText(this@RegCodeActivity, ""+it.msg, Toast.LENGTH_SHORT).show()
                    }
                    else->{}
                }
            }
        }
        db.btnSend.setOnClickListener {
            /*var time:Long=10*1000
            object :CountDownTimer(time,1000){
                override fun onTick(millisUntilFinished: Long) {
                    Log.i("===",millisUntilFinished.toString())
                    db.btnSend.text="验证码（${millisUntilFinished/1000%60} s）"
                    db.btnSend.isEnabled=false
                }

                override fun onFinish() {
                    db.btnSend.isEnabled=true
                    db.btnSend.text="重新发送"
                }

            }.start()*/
            handler.postDelayed(myTimer,0)

            val phone = db.etPhone.text.toString()
            if(phone.isEmpty()){
                Toast.makeText(this@RegCodeActivity, "输入不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if(!phone.matches(Regex("1[0-9]{10}"))){
                Toast.makeText(this@RegCodeActivity, "手机号格式有误", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            lifecycleScope.launch {
                vm.registerChannel.send(UserIntent.sendRegCode(phone))
            }
        }

        db.btnCoderegister.setOnClickListener {
            val phone = db.etPhone.text.toString()
            val code = db.etCode.text.toString()
            val pass = db.etPass.text.toString()
            val pass2 = db.etPass2.text.toString()
            if(phone.isEmpty()||pass.isEmpty()||pass2.isEmpty()||code.isEmpty()){
                Toast.makeText(this@RegCodeActivity, "输入不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if(!pass.matches(Regex("[0-9A-z_]{3,9}"))){
                Toast.makeText(this@RegCodeActivity, "需要输入字母数字下划线3-9位", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if(!pass.equals(pass2)){
                Toast.makeText(this@RegCodeActivity, "两次密码不一致", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            lifecycleScope.launch {
                val map = hashMapOf("phone" to phone, "password" to pass,"code" to code)
                val json= Gson().toJson(map)
                val body = RequestBody.create(MediaType.parse("application/json"), json)
                //发送验证码注册意图
                vm.registerChannel.send(UserIntent.registerCode(body))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //移除线程引用，防止内存泄漏
        handler.removeCallbacks(myTimer)
    }
}